package com.reverie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reverie.common.pojo.CommonPageReq;
import com.reverie.entity.CategoryRelGood;
import com.reverie.entity.GoodCategory;
import com.reverie.mapper.GoodCategoryMapper;
import com.reverie.service.ICategoryRelGoodService;
import com.reverie.service.IGoodCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class GoodCategoryServiceImpl extends ServiceImpl<GoodCategoryMapper, GoodCategory> implements IGoodCategoryService {

    @Resource
    private ICategoryRelGoodService categoryRelGoodService;

    @Override
    public Boolean saveGoods(GoodCategory goodCategory) {
        if (!CollectionUtils.isEmpty(goodCategory.getGoodList())) {
            categoryRelGoodService.removeByCategoryId(String.valueOf(goodCategory.getId()));
            List<CategoryRelGood> categoryRelGoods = new ArrayList<>();
            goodCategory.getGoodList().forEach(goods -> {
                CategoryRelGood categoryRelGood = new CategoryRelGood();
                categoryRelGood.setCategoryId(goodCategory.getId());
                categoryRelGood.setGoodId(goods.getGoodsId());
                categoryRelGood.setSortId(goods.getSortOrder());
                categoryRelGoods.add(categoryRelGood);
            });
            return categoryRelGoodService.saveOrUpdateBatch(categoryRelGoods);
        }
        return true;
    }

    @Override
    public Page<GoodCategory> queryPage(CommonPageReq<GoodCategory> pageReq) {
        GoodCategory queryParams = pageReq.getQueryParam();
        QueryWrapper<GoodCategory> wrapper = new QueryWrapper<>();
        if (queryParams != null) {
            if (queryParams.getPublished() != null) {
                wrapper.lambda().eq(GoodCategory::getPublished,queryParams.getPublished());
            }
            if (queryParams.getName() != null) {
                wrapper.lambda().like(GoodCategory::getName,queryParams.getName());
            }
        }
        wrapper.lambda().orderByAsc(GoodCategory::getSortId);
        Page<GoodCategory> categoryPage = new Page<>(pageReq.getPageNo(), pageReq.getPageSize());
        return page(categoryPage,wrapper);
    }
}
